#pragma once

/*
    日志落地模块
    1.抽象落地基类
    2.派生子类
    3.使用工厂模式进行创建于表示的分离
*/
#include <iostream>
#include <memory>
#include <fstream>
#include <string>
#include <cassert>
#include <ctime>
#include <sstream>
#include "util.hpp"

namespace jiuqilog
{
    class LogSink
    {
    public:
        using ptr = std::shared_ptr<LogSink>;
        virtual ~LogSink() {} // 用户扩展时可能会有需要释放的资源
        virtual void log(const char *data, size_t len) = 0;
    };

    // 标准输出
    class StdoutSink : public LogSink
    {
    public:
        void log(const char *data, size_t len)
        {
            std::cout.write(data, len);
        }
    };

    // 指定文件
    class FileSink : public LogSink
    {
    public:
        // 构造时传入一个文件名,打开文件,将文件句柄管理起来
        FileSink(const std::string &pathname)
            : _pathname(pathname)
        {
            // 创建日志文件所对应的目录
            util::File::create_directory(util::File::path(_pathname));
            // 创建日志文件
            _ofs.open(_pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }

        void log(const char *data, size_t len)
        {
            _ofs.write(data, len);
            //_ofs.flush();
            assert(_ofs.good());
        }

    private:
        std::string _pathname;
        std::ofstream _ofs;
    };

    class RollSinkBySize : public LogSink
    {
    public:
        RollSinkBySize(const std::string &basename, size_t max_fsize)
            : _basename(basename), _max_fsize(max_fsize)
        {
            std::string pathname = NewFile();
            // 创建日志文件所对应的目录
            util::File::create_directory(util::File::path(pathname));
            // 创建日志文件
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }

        void log(const char *data, size_t len)
        {
            // 写入前判断文件大小
            if (_cur_fsize + len >= _max_fsize)
            {
                _ofs.close();
                std::string filename = NewFile();
                _ofs.open(filename, std::ios::binary | std::ios::app);
                assert(_ofs.is_open());
                _cur_fsize = 0;
            }
            // 写入日志
            _ofs.write(data, len);
            //_ofs.flush();
            assert(_ofs.good());
            _cur_fsize += len;
        }

    private:
        std::string NewFile()
        {
            time_t time = util::Date::now();
            struct tm t;
            localtime_r(&time, &t);
            std::stringstream filename;
            filename << _basename << t.tm_year + 1900 << "-"
                     << t.tm_mon + 1 << "-" << t.tm_mday << "-"
                     << t.tm_hour << "-" << t.tm_min << "-"
                     << t.tm_sec << "-" << _num
                     << ".log";
            _num++;
            return filename.str();
        }

    private:
        std::string _basename; // 基础文件名
        std::ofstream _ofs;
        size_t _max_fsize;     // 文件最大大小
        size_t _cur_fsize = 0; // 当前文件已经写入的数据大小
        int _num = 0;          // 计数器
    };

    enum class GapType
    {
        GAP_SECOND,
        GAP_MINUTE,
        GAP_HOUR,
        GAP_DAY
    };
    class RollSinkByTime : public LogSink
    {
    public:
        RollSinkByTime(const std::string &basename, GapType gaptype)
            : _basename(basename)
        {
            initGapSize(gaptype);
            std::string pathname = NewFile();
            // 创建日志文件所对应的目录
            util::File::create_directory(util::File::path(pathname));
            // 创建日志文件
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = util::Date::now() / _gap_size;
        }

        void log(const char *data, size_t len)
        {
            // 写入前判断当前时间
            time_t now = util::Date::now();
            time_t current_gap = (now / _gap_size) * _gap_size;
            if (current_gap != _cur_gap)
            {
                _ofs.close();
                std::string filename = NewFile();
                _ofs.open(filename, std::ios::binary | std::ios::app);
                assert(_ofs.is_open());
                _cur_gap = current_gap;
            }
            // 写入日志
            _ofs.write(data, len);
            //_ofs.flush();
            assert(_ofs.good());
        }

    private:
        void initGapSize(GapType gaptype)
        {
            switch (gaptype)
            {
            case GapType::GAP_SECOND:
                _gap_size = 1;
                break;
            case GapType::GAP_MINUTE:
                _gap_size = 60;
                break;
            case GapType::GAP_HOUR:
                _gap_size = 3600;
                break;
            case GapType::GAP_DAY:
                _gap_size = 3600 * 24;
                break;
            }
        }
        std::string NewFile()
        {
            time_t time = util::Date::now();
            struct tm t;
            localtime_r(&time, &t);
            std::stringstream filename;
            filename << _basename << t.tm_year + 1900 << "-"
                     << t.tm_mon + 1 << "-" << t.tm_mday << "-"
                     << t.tm_hour << "-" << t.tm_min << "-"
                     << t.tm_sec << ".log";
            return filename.str();
        }

    private:
        std::string _basename; // 基础文件名
        std::ofstream _ofs;
        int _cur_gap;
        int _gap_size;
    };

    class SinkFactory
    {
    public:
        template <class SinkType, class... Args>
        static LogSink::ptr createSink(Args... args)
        {
            return std::make_shared<SinkType>(std::forward<Args>(args)...);
        }
    };
}